package org.fuckerfucker.todoapp_kotlin.data.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.fuckerfucker.todoapp_kotlin.data.TodoDB
import org.fuckerfucker.todoapp_kotlin.data.model.Todo
import org.fuckerfucker.todoapp_kotlin.data.repository.TodoRepo

class TodoViewModel(application: Application): AndroidViewModel(application) {

    // once get database instance, call the todoDao() as inner refer to TodoDao interface
    private val todoDao = TodoDB.getDB(application).todoDao()

    private val repository: TodoRepo = TodoRepo(todoDao)

    val getAllData: LiveData<List<Todo>> = repository.getAllData

    val sortByHighPriority: LiveData<List<Todo>> = repository.sortByHighPriority
    val sortByLowPriority: LiveData<List<Todo>> = repository.sortByLowPriority

    fun insertData(todo: Todo) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.insertOne(todo)
        }
    }

    fun updateData(todo: Todo) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateOne(todo)
        }
    }

    fun deleteItem (todo: Todo) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteItem(todo)
        }
    }

    fun deleteAll() {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteAll()
        }
    }

    fun searchDatabase(searchQuery: String): LiveData<List<Todo>> {
        return repository.searchDatabase(searchQuery)
    }
}